#!/usr/bin/env python3

# Written by Pedro Gimeno
# args: infile outfile savename startaddr [execaddr]
#       execaddr defaults to startaddr
# For lack of knowledge, currently only executable binaries are supported.

import sys, struct

def main():
  if len(sys.argv) < 5:
    sys.stderr.write("Usage: raw2cas.py infile outfile filename6chars startaddr"
                     " [execaddr]\n")
    return

  start = int(sys.argv[4], 0) & 0xFFFF
  if len(sys.argv) > 5:
    exe = int(sys.argv[5], 0)
  else:
    exe = start

  h = b'\x1F\xA6\xDE\xBA\xCC\x13\x7D\x74'
  if sys.argv[1] != '-':
    f = open(sys.argv[1], 'rb')
    try:
      data = f.read()
    finally:
      f.close()
  else:
    data = sys.stdin.read()

  end = start + len(data) - 1

  nam = ('%-6.6s' % sys.argv[3]).encode('latin1')

  if sys.argv[2] != '-':
    g = open(sys.argv[2], 'wb')
  else:
    g = sys.stdout.buffer
  try:
    # Block 1
    g.write(h)
    g.write(b'\xD0' * 10)
    g.write(nam)

    # Block 2
    g.write(h)
    g.write(struct.pack('<HHH', start, end, exe))
    g.write(data)
    g.write(b'\0' * (-len(data) & 7))
  finally:
    if sys.argv[2] != '-':
      g.close()

main()
